<?php
global $smarty;

$thisPage = "maintenance";

TemplateHelper::useLayout("default", true);


addDataService("upload");
addDataservice("inserttmp");
addDataService("getuploadedcompanies");
addDataservice("finalize");
addDataService("rollback");
addDataService("getnousercompanies");
addDataservice("generateusers");

$exportimport = array(
            "companyname",
            "address",
            "phone1",
            "fax1",
            "email1",
            "hphungarian",
            "contactperson1",
            "jobtitle1",
            "freetype_text",
            "product_hs4code",
);

$businessleads = array(
            "companyname",
            "address",
            "phone1",
            "fax1",
            "email1",
            "hphungarian",
            "contactperson1",
            "jobtitle1",
            "buysell",
            "hs4",
            "product",
            "description",
            "quantity",
            "unit",
            "origin",
            "destination",
);

$recommendedservices = array(
            "companyname",
            "address",
            "phone1",
            "fax1",
            "email1",
            "hphungarian",
            "contactperson1",
            "jobtitle1",
            "service_type",
            "service_description",
);

$abroad = array(
    "companyname",
    "country",
    "address",
    "hphungarian",
    "email1",
    "phone1",
    "fax1",
    "contactperson1",
    "contactperson2",
    "freetype_text",
);

$maintenanceTypes = array();
$maintenanceTypes[] = array(type => "company_upload", title => "Upload companies", content => getTabContent("company_upload", $smarty));
$maintenanceTypes[] = array(type => "userpwgen", title => "Username/password creation", content => getTabcontent("userpwgen", $smarty));

function buildLayout($smarty) {
    $smarty->assign("default", array(
        content => getContent($smarty),
        contexthelp => getContextHelp($smarty),
    ));
}

function executeService($serviceName, $params) {
    switch ($serviceName) {
        case "upload" : { return service_upload($params); }
        case "validatecompanies" : { return service_validatecompanies($params); }
        case "inserttmp" : { return service_inserttmp($params); }
        case "getuploadedcompanies": { return service_getuploadedcompanies($params); }
        case "finalize" : { return service_finalize($params); }
        case "rollback" : { return service_rollback($params); }
        case "getnousercompanies" : { return service_getnousercompanies($params); }
        case "generateusers" : { return service_generateusers($params); }
    }
}

function service_upload($params) {
    move_uploaded_file($_FILES['company_import']['tmp_name'], "site/resources/upload/" . $_FILES['company_import']['name']);
    storeParameter("importfile", $_FILES['company_import']['name']);
    Importer::init("site/resources/upload/".$_FILES['company_import']['name']);
    return serviceSuccessful(array(
    ));
}

function service_finalize($params) {
    Database::loadModel("companies");
    Database::getModel()->importUploadedCompanies();
    Database::getModel()->updateMV();
    return serviceSuccessful(array(
    ));
}

function service_rollback($params) {
    Database::loadModel("companies");
    Database::getModel()->rollbackUploadedCompanies();
    return serviceSuccessful(array());
}

function service_generateusers($params) {
    Database::loadModel("companies");
    $users = Database::getModel()->generateUsers();
/*
    $delays = 0;
    for ($i = 0; $i < count($users); $i++) {
        if ($i > 0 && $i % 50 == 0) { $delays++; }
        $emailData = getEmailText("usercreated", $users[$i]);
        Database::loadModel("tasks");
        Database::getModel()->addEmailTask($users[$i]['email'], $emailData['subject'], $emailData['content'], date("Y-m-d", time() + $delays * 24*60*60));
    }
*/
    return serviceSuccessful(array());
}

function service_getuploadedcompanies($params) {
    Database::loadModel("companies");
    Database::getModel()->setPageData(getRequestParameter("pg"), getRequestParameter("rows"));
    $result = Database::getModel()->getUploadedCompanies();
    $reccount = Database::getModel()->getUploadedCompaniesCount();
    $limit = intval(getRequestParameter("rows"), 10);
    return array(
        page => getRequestParameter("pg"),
        total => ceil($reccount/$limit),
        rows => JQGridHelper::convert($result, "company_id"),
        records => $reccount,
    );
}

function service_getnousercompanies($params) {
    Database::loadModel("companies");
    Database::getModel()->setPageData(getRequestParameter("pg"), getRequestParameter("rows"));
    $result = Database::getModel()->getNoUserCompanies();
    $reccount = Database::getModel()->getNoUserCompaniesCount();
    $limit = intval(getRequestParameter("rows"), 10);
    return array(
        page => getRequestParameter("pg"),
        total => ceil($reccount/$limit),
        rows => JQGridHelper::convert($result, "company_id"),
        records => $reccount,
    );
}

function service_validatecompanies($params) {
    global $exportimport;
    global $businessleads;
    global $recommendedservices;
    global $abroad;

    Importer::init("site/resources/upload/".getStoredParameter("importfile"));
    if (in_array($params['type'], array("1", "2"))) {
        Importer::setColumnList($exportimport);
    } else if (in_array($params['type'], array("3", "4"))) {
        Importer::setColumnList($abroad);
    } else if ($params['type'] == "5") {
        Importer::setColumnList($recommendedservices);
    } else if ($params['type'] == "6") {
        Importer::setColumnList($businessleads);
    }
    $result = Importer::validate($params);
    return $result;
}

function service_inserttmp($params) {
    global $exportimport;
    global $businessleads;
    global $recommendedservices;
    global $abroad;

    Importer::init("site/resources/upload/".getStoredParameter("importfile"));
    if (in_array($params['type'], array("1", "2"))) {
        Importer::setColumnList($exportimport);
    } else if (in_array($params['type'], array("3", "4"))) {
        Importer::setColumnList($abroad);
    } else if ($params['type'] == "5") {
        Importer::setColumnList($recommendedservices);
    } else if ($params['type'] == "6") {
        Importer::setColumnList($businessleads);
    }
    $rows = array();
    $query = "INSERT INTO companies (companyname, address, phone1, fax1, email1, hphungarian, contactperson1, jobtitle1, uploaded) VALUES ";
    while (($row = Importer::getNextRow()) !== false) {
        $query  = "INSERT INTO companies (companyname, country, address, phone1, fax1, email1, hphungarian, contactperson1, jobtitle1, is_habroad, uploaded) VALUES (".
                  "'".Importer::getColumn($row, "companyname")."',".
                  "'" . ($params['type'] == "3" || $params['type'] == "4" ? Importer::getColumn($row, "country") : "Hungary") . "',".
                  "'".Importer::getColumn($row, "address")."',".
                  "'".Importer::getColumn($row, "phone1")."',".
                  "'".Importer::getColumn($row, "fax1")."',".
                  "'".Importer::getColumn($row, "email1")."',".
                  "'".Importer::getColumn($row, "hphungarian")."',".
                  "'".Importer::getColumn($row, "contactperson1")."',".
                  "'".Importer::getColumn($row, "jobtitle1")."',".
                  ($params['type'] == "3" || $params['type'] == "4" ? "1" : "0").
                  ",1".
                  ")"
        ;
        Database::executeQuery($query);
        $id = Database::getInsertedId();
        if (in_array($params['type'], array("1", "2"))) {
            $hs4codes = explode(",", Importer::getColumn($row, "product_hs4code"));
            for ($i = 0; $i < count($hs4codes); $i++) {
                $query = "INSERT INTO company_hs4_conn (company_id, hs4_id, imp_exp, freetype_text, uploaded) VALUES (".
                     $id.",".
                     "'".rtrim(ltrim($hs4codes[$i]))."',".
                     "'".($params['type'] == "1" || $params['type'] == "3" ? "2" : "1")."',".
                     "'".Importer::getColumn($row, "freetype_text")."',".
                     "1".
                     ")"
                ;
                Database::executeQuery($query);
                if ($params['type'] == "1") {
                    $query = "INSERT INTO company_hs4_conn (company_id, hs4_id, imp_exp, freetype_text, uploaded) VALUES (".
                         $id.",".
                         "'".rtrim(ltrim($hs4codes[$i]))."',".
                         "'1',".
                         "'Equipment, products, and materials to produce, package, or deliver ".Importer::getColumn($row, "freetype_text")."',".
                         "1".
                         ")"
                    ;
                    Database::executeQuery($query);
                }
            }
        } else if (in_array($params['type'], array("3", "4"))) {
            $query = "INSERT INTO company_hs4_conn (company_id, freetype_text, uploaded) VALUES (".
                     $id.",".
                     "'".Importer::getColumn($row, "freetype_text")."',".
                     "1".
                     ")"
            ;
            Database::executeQuery($query);
        } else if ($params['type'] == "5") {
            $query = "INSERT INTO recommended_services (company_id, service_description, service_type, uploaded) VALUES (".
                    $id.",".
                    "'" . Importer::getColumn($row, "service_description")."',".
                    "'" . Importer::getColumn($row, "service_type")."',".
                    "1".
                    ")";
            Database::executeQuery($query);
        } else if ($params['type'] == "6") {
            $query = "INSERT INTO businessleads (company_id, productname,postdate,hs4,quantity,description,unit,country_origin,country_dest,buysell, uploaded) VALUES (".
                    $id.",".
                    "'" . Importer::getColumn($row, "product")."',".
                    "now(),".
                    "'" . Importer::getColumn($row, "hs4")."',".
                    "'" . Importer::getColumn($row, "quantity")."',".
                    "'" . Importer::getColumn($row, "description")."',".
                    "'" . Importer::getColumn($row, "unit")."',".
                    "'" . Importer::getColumn($row, "origin")."',".
                    "'" . Importer::getColumn($row, "destination")."',".
                    (Importer::getColumn($row, "buysell") == "buy" ? "1" : "2").",".
                    "1".
                    ")";
            Database::executeQuery($query);
        }
    }
    return serviceSuccessful(array(
    ));
}

function getTabContent($tabName, $smarty) {
    switch ($tabName) {
        case "company_upload" : { return getCompanyUploadTabcontent($smarty); }
        case "userpwgen" : { return getUserPwGenTabContent($smarty); }
    }
}

function getUserPwGenTabContent($smarty) {
    global $thisPage;

    return $smarty->fetch(TemplateHelper::getTemplateFile($thisPage, "tab.userpwgen", true));
}

function getCompanyUploadTabContent($smarty) {
    global $thisPage;

    return $smarty->fetch(TemplateHelper::getTemplateFile($thisPage, "tab.companyupload", true));
}

function getContent($smarty) {
    global $thisPage;
    global $maintenanceTypes;
    
    $smarty->assign("maintenancetypes", $maintenanceTypes);
    return $smarty->fetch(TemplateHelper::getTemplateFile($thisPage, "content", true));
}

function getContextHelp($smarty) {
    global $thisPage;
    
    return $smarty->fetch(TemplateHelper::getTemplateFile($thisPage, "contexthelp", true));
}

function getPageHeader() {
}

function getPageFooter() {
}

?>
